<template>
	<div class="box">
		<!-- 头部搜索模块 -->
		<headerSearch 
      :selectObj="selectObject" 
      :goSearchFc="searchClick" 
      :addFun="addDrawerForm" 
      :examine="examine" 
      :buttonList="buttonList"
    />
		<!-- 中间表格模块 -->
        <BaseTable
            :data="cargotableData"
            :columns="cargotableDataColumns"
            :tableHeight="tableHeight"
            :pagination="false"
            :loading="loading"
            @details="tableClick"
        ></BaseTable>

		<div class="page">
			<el-pagination
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="queryAll.startpage"
				:page-sizes="[10, 15, 20, 25, 30]"
				:page-size="queryAll.pagesize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalNum"
			></el-pagination>
		</div>


		<!-- 新增编辑 -->
		<el-drawer
			:before-close="handleClose"
			:title="statusMap[status] + (activeName === 'first' ? '船舶信息' : '货物信息')"
			:visible.sync="drawerInner"
			direction="rtl"
      @open="openDrawer"
			size="60%"
		>
    <!-- 新增编辑 -->
      <!-- <shipDetail
        v-if="status === 'add' || status === 'edit'"
        :compData="compData"
        :customerData="customerData"
        ref="addDetail"
        :status="status"
      /> -->
    <!-- 确报页面 -->
      <el-tabs v-model="activeName" @tab-click="handleAcitveClick" type="border-card" style="box-shadow:none;border:none">
        <el-tab-pane label="船舶信息" name="first" :disabled="isShip">
          <shipDetail
            :compData="compData"
            :customerData="customerData"
            ref="addDetail"
            :status="status"
            :fileList="shipFileList"
          />
        </el-tab-pane>
        <el-tab-pane label="作业指令" name="second" :disabled="isConfirmation">
          <cargoDetail :status="status" ref="cargoDetail" :fileList="cargoFileList"/>
        </el-tab-pane>
      </el-tabs>
			<div class="demo-drawer__footer">
				<el-button type="primary" :disabled="(activeName === 'second'? !isShip: false)" @click="submitInner('2')" v-if="!isGet" size="mini">{{activeName === 'first'?'保存并确报':'保存并发布'}}</el-button>
				<el-button type="primary" @click="submitInner('1')" size="mini" v-if="!isGet">保 存</el-button>
        <el-button size="mini" @click="drawerInner = false">取消</el-button>
			</div>
		</el-drawer>
	</div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/Business/reportingReview'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
import shipDetail from './shipDetail.vue'
import cargoDetail from './cargoDetail.vue'
export default {
  name: 'reportingReview',
  components: {
    BaseTable,
    headerSearch,
    shipDetail,
    cargoDetail
  },
  data() {
    return {
      // 搜索框显示对象
      selectObject: [
        {
          name: '船名航次',
          type: 'input',
          modelName: 'shipvoyageName'
        },
        {
          name: '船代',
          type: 'select',
          modelName: 'customerId',
          selectLabel: 'customerName',
          selectValue: 'customerId',
          selectData: []
        },
        {
          name: '货代',
          type: 'select',
          modelName: 'cargoAgentId',
          selectLabel: 'customerName',
          selectValue: 'customerId',
          selectData: []
        }
      ],
      // 按钮的list
      buttonList: [
        { label: '新建', type: 'primary', icon: 'el-icon-plus', click: () => this.addDrawerForm, permission: 'businessManagement:reportingReview:add' },
        { label: '确报', type: 'primary', icon: 'el-icon-finished', click: () => this.examine, permission: 'businessManagement:reportingReview:examine', disabled: true }
      ],
      cargotableDataColumns: [ // table表头shipvoyageName
        { prop: 'shipvoyageName', width: 120, label: '船名航次', render: (h, params) => {
          return h(
            'div',
            [
              h('span', {
                props: {
                  size: 'mini'
                },

                domProps: {
                  // 添加标签,使用自己引入的iconfont图标
                  innerHTML:
											`<span style='color:rgb(64, 158, 255);text-decoration: underline;cursor:pointer'><span  style='padding-left:5px;'>${params.row.shipvoyageName}</span></span>`
                },
                on: {
                  click: () => {
                    this.handleEditOut(params.row, 'get')
                  }
                }
              })
            ]
          )
        } },
        { prop: 'shipNameEn', label: '英文船名' },
        { prop: 'cargoCategoryName', label: '货种' },
        { prop: 'actualLoad', label: '载货量' },
        { prop: 'tradeType', label: '贸别' },
        { prop: 'loadUnload', label: '装卸' },
        { prop: 'portName', label: '起运港/目的港' },
        { prop: 'customerName', label: '船代', isShort: true },
        { prop: 'cargoOwnerName', label: '货主', isShort: true },
        { prop: 'cargoAgentName', label: '货代', isShort: true },
        { prop: 'issuingCompanyName', label: '开证公司', isShort: true },
        { prop: 'arrivalTimePlan', label: '预抵日期' },
        {
          prop: 'statusLabel',
          label: '报港状态',
          render: (h, params) => {
            let status = ''
            this.statusData.filter(item => {
              if (item.dictValue === params.row.status) {
                status = item.dictLabel
              }
            })
            return h('el-tag', {
              props: {
                size: 'mini',
                type: 'success'
              },
              domProps: {
                innerHTML: status
              }
            })
          }
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 150,
          render: (h, params) => {
            return h(
              'div',

              [
                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: Number(params.row.status) >= '2' && (Number(params.row.trustStatus) >= '3')
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML:
											"<span style='color:#0B6CD6'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>"
                  },
                  on: {
                    click: () => {
                      this.handleEditOut(params.row)
                    }
                  }
                }),

                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.status !== '1'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    // innerHTML: `<i class="iconfont icon-tubiao_liebiaoshanchu" style="color:#DA2821"></i> 删除`
                    innerHTML: `<span style='color:#F75E5E'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleDelete(params.row.id)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      cargotableData: [], // 船舶信息data
      compData: [], // 业务单元数据
      customerData: [], // 船代货代数据
      statusData: [], // 状态数组
      activeName: 'first',
      status: 'add', // 当前状态
      statusMap: {
        add: '新建',
        edit: '修改',
        examine: '确报'
      },
      isConfirmation: false, // 是否可以访问货物信息
      isShip: false, // 是否可以访问船舶信息,false是可以，true是不可以
      isGet: false, // 是否是查看，true是，false不是，查看模式隐藏按钮
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        portName: '',
        customerId: '',
        cargoCategoryCode: ''
      },
      totalNum: 0,
      drawerInner: false,
      clickRow: {},
      shipFileList: [],
      cargoFileList: []
    }
  },
  async activated() {
    this.getComp()
    this.getStatus()
    this.getCustomer()
  },
  computed: {
    tableHeight: function() {
      return this.$store.state.tableHeight - 40
    }
  },
  methods: {
    /**
     * 查询船舶信息
     */
    async getBoatList() {
      this.loading = true
      await api
        .reqGetBoat(this.queryAll)
        .then(res => {
          this.loading = false
          this.buttonList[1].disabled = true
          this.cargotableData = res.data.data.pages
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.totalNum = res.data.data.totalNum
        })
        .catch(() => {})
    },
    /**
     * 新建
     */
    addDrawerForm() {
      this.drawerInner = true
      this.status = 'add'
      this.isConfirmation = true // 新建进来货物信息不可进
      this.activeName = 'first' // 新建进来默认显示船舶信息
      this.isShip = false
      this.isGet = false
    },
    /**
     * 编辑查询 - 船舶信息
     */
    async handleEditOut(row, type) {
      this.isGet = false
      if (type === 'get') this.isGet = true
      this.drawerInner = true
      this.status = 'edit'
      if (row.status !== '1' && (row.trustStatus === '1' || row.trustStatus === null) && type !== 'get') { // 船舶确报则直接打开指令
        this.activeName = 'second'
        this.isShip = true
        this.isConfirmation = false // 货物信息可进
        this.$nextTick(() => {
          setTimeout(() => {
            this.getCargoInformation(this.clickRow)
          }, 100);
        })
      } else { // 船舶信息没有确报
        this.activeName = 'first'
        this.isShip = false
        this.isConfirmation = false
        const res = await api.reqEditBoat({ id: row.shipId }) // 获取船舶信息
        const res1 = await api.reqEditPrediction({ id: row.id }) // 获取航次信息
        this.$nextTick(() => {
          this.$refs.addDetail.formData = res.data.data
          this.$refs.addDetail.vFormData = res1.data.data
          this.$refs.addDetail.billList = res1.data.data.billList
          this.shipFileList = res1.data.data.attachmentInfoList.map(item => {
            item.name = item.fileName
            item.fileFormat = item.fileName.split('.')[1]
            return item
          })
          if (res1.data.data.assistWorkName === null) {
            this.$refs.addDetail.vFormData.assistWorkName = []
          } else {
            this.$refs.addDetail.vFormData.assistWorkName = res1.data.data.assistWorkName.split(',')
          }
        })
      }
    },
    /**
     * 新建、编辑保存
     */
    async submitInner(status) {
      if (this.activeName === 'first') {
        this.shipSave(status)
      } else {
        this.cargoSave(status)
      }
    },
    // 船舶信息保存
    async shipSave(status) {
      const params = Object.assign(this.$refs.addDetail.formData, this.$refs.addDetail.vFormData)
      if (this.status === 'add') { // 新建进来去掉id
        delete params.id
      }
      params.billList = this.$refs.addDetail.billList
      params.assistWork = []
      if (params.assistWorkName !== null) {
        params.assistWorkName.forEach(item => {
          this.$refs.addDetail.processData.forEach(i => {
            if (item === i.processName) {
              params.assistWork.push(i.processCode)
            }
          })
        })
        params.assistWorkName = params.assistWorkName.join()
        params.assistWork = params.assistWork.join()
      }
      params.status = status // 修改状态，保存1/保存并确保2
      this.$refs.addDetail.$refs.vRuleForm.validate((valid) => {
        if (valid) {
          if (!params.shipName) {
            this.$message.warning('请选择船名！')
            return
          } else if (!params.companyId) {
            this.$message.warning('请选择组织！')
            return
          } else if (params.billList.length === 0 && params.loadUnload === '卸') {
            this.$message.warning('请添加提单信息！')
            return
          }
          api.reqAddBoat(params).then(res => {
            if (res.data.code === '0000') {
              this.getBoatList()
              this.$message.success(this.statusMap[this.status] + '成功')
              // 跳转到货物信息,给货物信息赋值
              this.activeName = 'second'
              this.getCargoInformation(res.data.data)
              this.clickRow = res.data.data // 将保存后返回的船舶信息数据赋值给clickRow,便于切换tab时数据正确
              this.isConfirmation = false
              if (status === '2') this.isShip = true
              // this.drawerInner = false
              // this.getBoatList()
            }
          })
        } else {
          this.$message.warning('请完善表单信息！')
          return false;
        }
      });
    },
    /**
     * 货物信息带过来的部分赋值
     */
    async getCargoInformation(data) {
      this.$refs.cargoDetail.getShipvoyage()
      this.$refs.cargoDetail.source = data.loadUnload === '装' ? '3' : '1'
      this.$refs.cargoDetail.destination = data.loadUnload === '装' ? '1' : '3'
      this.$refs.cargoDetail.shipFormData.id = data.id // 保存之后把新的航次id赋值给指令
      this.$refs.cargoDetail.changeShipVoyage(data.id)
      this.$refs.cargoDetail.formData.companyId = data.companyId // 指令中的组织
      this.$refs.cargoDetail.formData.cargoCategoryCode = data.cargoCategoryCode // 指令中的货种
      this.$refs.cargoDetail.formData.tradeType = data.tradeType // 指令中的贸别
      if (data.loadUnload === '装') {
        this.$refs.cargoDetail.formData.processCode = 'CHANG/CHUAN'
      } else if (data.loadUnload === '卸') {
        this.$refs.cargoDetail.formData.processCode = 'CHUAN/CHANG'
      }
      if (data.trustStatus !== null) { // 只要保存过指令就查
        this.editTrust(this.clickRow.trustId)
      }
    },
    /**
     * 货物信息编辑查询
     */
    async editTrust(id) {
      const res = await api.reqEditTrust(id)
      this.$nextTick(() => {
        this.$refs.cargoDetail.formData.customerName = res.data.data.customerName.split(',')
        this.$refs.cargoDetail.formData.customerId = res.data.data.customerId.split(',')
        this.$refs.cargoDetail.formData.paymentStatus = res.data.data.paymentStatus
        this.$refs.cargoDetail.formData.preAmount = res.data.data.preAmount
        this.$refs.cargoDetail.formData.planCarNum = res.data.data.planCarNum
        this.$refs.cargoDetail.formData.remark = res.data.data.remark
        this.$refs.cargoDetail.formData.trustNo = res.data.data.trustNo
        this.$refs.cargoDetail.formData.id = res.data.data.id
        this.$refs.cargoDetail.billList = res.data.data.billList
        // this.detailFormData = JSON.parse(JSON.stringify(this.$refs.detail.formData))
        this.cargoFileList = res.data.data.mattachmentInfoList.map(item => {
          item.name = item.fileName
          item.fileFormat = item.fileName.split('.')[1]
          return item
        })
      })
    },
    // 货物信息保存
    async cargoSave(status) {
      const form = JSON.parse(JSON.stringify(this.$refs.cargoDetail.formData))
      if (status === '2') {
        form.status = '3'
      }
      form.customerName = form.customerName.join()
      form.customerId = form.customerId.join()
      form.billList = JSON.parse(JSON.stringify(this.$refs.cargoDetail.billList))
      this.$refs.cargoDetail.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!form.companyId) {
            this.$message.warning('请选择组织！')
            return
          } else if (!form.shipvoyageId && (this.$refs.cargoDetail.source === '1' || this.$refs.cargoDetail.destination === '1')) { // 只要有船名航次就要控制
            this.$message.warning('请选择船名航次！')
            return
          } else if (form.billList.length === 0 && this.$refs.cargoDetail.destination !== '5') {
            this.$message.warning('请填写提单信息！')
            return
          } else if (this.$refs.cargoDetail.source !== '1' && this.$refs.cargoDetail.destination !== '1') { // 需自行添加部分，控制必填项
            let num = 0
            form.billList.forEach(item => {
              for (const key in item) {
                const element = item[key];
                if (!element && (key !== 'billNo' || key !== 'quantity' || key !== 'ton' || key !== 'volume')) {
                  this.$message.warning('请完善提单信息！')
                  num++
                  return
                }
              }
            })
            if (num > 0) {
              return
            }
          }
          if (form.trustNo) { // 修改
            api.reqUpdateTrust(form).then(res => {
              if (res.data.code === '0000') {
                this.$message.success('修改成功')
                this.drawerInner = false
                this.getBoatList()
              }
            })
          } else { // 新建
            api.reqAddTrust(form).then(res => {
              if (res.data.code === '0000') {
                this.$message.success('新增成功')
                this.drawerInner = false
                this.getBoatList()
              }
            })
          }
        } else {
          this.$message.warning('请完善表单信息！')
          return false;
        }
      });
    },
    /**
     * 删除主列表船舶预报信息
     */
    async handleDelete(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDelete(id).then(res => {
          if (res.data.code === '0000') {
            this.getBoatList()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 确报
     */
    async examine() {
      this.handleEditOut(this.clickRow)
      this.status = 'examine'
    },
    /**
     * 获取行信息
     */
    tableClick(row) {
      this.clickRow = row
      if (row.status === '2' && (row.trustStatus === '3' || row.trustStatus === '4' || row.trustStatus === '5')) {
        this.buttonList[1].disabled = true
      } else {
        this.buttonList[1].disabled = false
      }
    },
    /**
     * 获取业务单元
     */
    async getComp() {
      const res = await publicapi.getListComp()
      this.compData = res.data.data
    },
    /**
     * 获取船代货代
     */
    async getCustomer() {
      const res = await publicapi.getlistCustomer()
      this.customerData = res.data.data
      this.selectObject[1].selectData = this.customerData
      this.selectObject[2].selectData = this.customerData
    },
    /**
     * 获取状态
     */
    async getStatus() {
      const res = await publicapi.getDictData('SHIPSTATUS')
      this.statusData = res.data.data.SHIPSTATUS
    },
    /**
     * 重置新增页面
     */
    resetForm() {
      // 清空船舶信息中的信息
      this.$refs.addDetail.formData.shipId = '' // 清空组织
      this.$refs.addDetail.vFormData.companyId = '' // 清空组织
      this.$refs.addDetail.vFormData.attachmentInfoList = [] // 清空上传文件
      this.$bus.$emit('resetFileList')
      this.$refs.addDetail.$refs.ruleForm.resetFields()
      this.$refs.addDetail.$refs.vRuleForm.resetFields()
      this.$refs.addDetail.billList = []
      // 清空货物信息中的信息
      this.$refs.cargoDetail.formData.trustNo = ''
      this.$refs.cargoDetail.formData.customerId = []
      this.$refs.cargoDetail.formData.paymentStatus = ''
      this.$refs.cargoDetail.formData.preAmount = ''
      this.$refs.cargoDetail.formData.planCarNum = ''
      this.$refs.cargoDetail.formData.remark = ''
      this.$refs.cargoDetail.formData.shipvoyageId = ''
      this.$bus.$emit('resetFileList')
      this.$refs.cargoDetail.billList = []
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.getBoatList()
    },
    handleAcitveClick(tab) {
      this.queryAll.startpage = 1
      this.queryAll.pagesize = 10
      console.log(tab, 'tab');
      if (tab.index === '1') {
        const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
        if (!isEmpty(this.clickRow)) {
          this.$nextTick(() => {
            this.getCargoInformation(this.clickRow)
          })
        }
      }
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getBoatList()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getBoatList()
    },
    /**
     * 打开抽屉的回调,将对应抽屉的form表单清空
     */
    openDrawer() {
      if (this.drawerInner) { // 新建编辑
        this.$nextTick(() => {
          this.resetForm()
        })
      }
    },
    handleClose(done) {
      let oldFormData = {}
      let oldvFormData = {}
      let newFormData = {}
      let newvFormData = {}
      if (this.drawerInner && this.status === 'add') {
        oldFormData = {
          shipId: '',
          shipName: '',
          hatchNo: '',
          shipLength: '',
          shipWidth: '',
          totalTon: '',
          netTon: '',
          weightTon: ''
        }
        oldvFormData = {
          companyName: '',
          companyId: '',
          voyage: '',
          cargoCategoryCode: '',
          arrivalTimePlan: '',
          loadUnload: '',
          tradeType: '',
          customerId: '',
          startPortCode: '',
          endPortCode: '',
          shipPhone: '',
          prePortCode: '',
          nextPortCode: '',
          pilotage: '',
          bowDraft: '',
          sternDraft: '',
          reqTug: '',
          tugNumber: '',
          halfLoad: '',
          actualLoad: '',
          remark: '',
          assistWorkName: [],
          billList: [],
          attachmentInfoList: []
        }
        newFormData = this.$refs.addDetail.formData
        newvFormData = this.$refs.addDetail.vFormData
        console.log({ oldFormData, newFormData, oldvFormData, newvFormData });
      }

      if (!Utils.compareData(oldFormData, newFormData)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
            this.getBoatList()
          })
          .catch(_ => {})
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "~@/assets/form.less";
.selectBox {
	justify-content: space-between;
	display: flex;
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-bottom: 0;
	border-left: none;
	height: 50px;
	position: relative;
	align-items: center;
	padding-left: 14px;
	padding-right: 20px;
}
.input_box {
	display: flex;
}
.page {
	background: #ffffff;
	text-align: right;
	border-radius: 0 0 4px 4px;
	padding: 5px 20px;
}
/deep/.el-tabs--border-card > .el-tabs__content {
	padding: 0 !important;
}
//抽屉底部样式
/deep/ .el-drawer__header {
	margin-bottom: 0;
	padding: 16px;
	border-bottom: 1px solid gainsboro;
}
.demo-drawer__footer {
	text-align: right;
	padding-right: 20px;
	border-top: 1px solid #c8cfde;
	background-color: #f5f7fa;
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	line-height: 50px;
}
.box {
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-radius: 4px 4px 0 0;
	border-top: none;
}
</style>
